<!--
 * @title: 销售项目运作抽屉组件
 * @params: id，销售项目id
 * @params: projectcode，销售项目编号
!-->
<template>
  <tl-sub-page :render="render" :modal="!isChildPage" :class="`tl-drawer ${isChildPage ? 'frame-drawer' : ''}`" ref="drawerRef" :visible.sync="visible" :with-header="false" :size="'95%'" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" @open="open" @close="close" :destroy-on-close="true" :wrapper-closable="false">
    <div :key="defaultApp" v-if="visible">
      <transition name="component-change" mode="out-in">
        <div class="customer-container" v-show="currentApp === defaultApp">
          <div style="width:0px;overflow:hidden;height:0px;"><input type="text" /></div>
          <div class="customer-header">
            <div class="info">
              <svg-icon icon-class="projectlogo" class="logo" :style="{ fill: $store.getters.theme, width: '55px', height: '55px' }"></svg-icon>
              <div class="content">
                <p class="contentOffset">
                  <el-tooltip effect="dark" :disabled="!projectinfo.projectname || projectinfo.projectname.length < 60" :content="projectinfo.projectname" placement="bottom">
                    <span class="longTitle">项目名称： {{ projectinfo.projectname ? projectinfo.projectname : '暂无' }}</span>
                  </el-tooltip>
                  <span>
                    <el-tag v-if="projectinfo.abnormalstate === 30" color="#D80A1E" size="medium" effect="dark">
                      {{ projectinfo.dispabnormalstate }}
                    </el-tag>
                    <el-tag v-else-if="projectinfo.abnormalstate === 20" color="#FF8C2E" size="medium" effect="dark">
                      {{ projectinfo.dispabnormalstate }}
                    </el-tag>
                    <el-tag v-else-if="projectinfo.abnormalstate === 15" color="#0000FF" size="medium" effect="dark">
                      {{ projectinfo.dispabnormalstate }}
                    </el-tag>
                    <el-tag v-else-if="projectinfo.abnormalstate === 10" color="#B8860B" size="medium" effect="dark">
                      {{ projectinfo.dispabnormalstate }}
                    </el-tag>
                    <el-tag v-else-if="projectinfo.abnormalstate === 0" type="success" size="medium" effect="dark">
                      {{ projectinfo.dispabnormalstate }}
                    </el-tag>
                  </span>
                </p>
                <p class="contentOffset">
                  <span>项目编号：{{ projectinfo.projectcode ? projectinfo.projectcode : '暂无' }}</span>
                  <span>项目经理：{{ projectinfo.projectmanager ? projectinfo.projectmanager : '暂无' }}</span>
                  <span>项目级别：{{ projectinfo.dispprojectlevel ? projectinfo.dispprojectlevel : '暂无' }} </span>
                </p>
              </div>
            </div>
            <div class="toolbar">
              <el-button type="danger" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
            </div>
          </div>
          <fold-nav-bar :height="mainHeight" :navList="navList" @clickNav="clickNav">
            <ul class="nav-list">
              <template v-for="(item, index) in navList">
                <li :key="index" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
                  <span style="float: left;" :class="{ navTextDis: item.count === 0 }">{{ item.name }}</span>
                  <span style="float: left;">
                    <i :class="[item.count > 0 ? 'navNum' : 'navNumDis']">{{ item.count }}</i>
                    <label v-if="item.flag">{{ item.flag }}</label>
                  </span>
                </li>
              </template>
            </ul>
          </fold-nav-bar>
          <div class="customer-main" :style="{ height: mainHeight + 'px' }">
            <el-scrollbar class="customer-main-container" id="mpmFileMainContainer">
              <div style="padding:0 10px">
                <projectItemTab v-if="projectinfo" :projectRoleCode="projectRoleCode" :projectinfo="projectinfo" :fromIndexType="'file'" ref="projectItemTabComponent"></projectItemTab>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </transition>
      <template v-for="nav in navList.filter((m) => m.useIframe)">
        <transition name="component-change" mode="out-in" :key="nav.code">
          <div v-if="!isChildPage && !isShowComponent(nav)" v-show="currentApp === nav.code && currentApp !== defaultApp" class="modal-container">
            <tl-iframe :ref="`frame_${nav.code}`" :id="`frame_${nav.code}`" startMethod="iframeOpen" :url="nav.frameUrl" @cancel="visible = false" :transparentBg="true" :isChildFrame="true" @openApp="openApp" :path="nav.framePath" :data="nav.iframeDatas" width="100%" height="100%"></tl-iframe>
          </div>
        </transition>
      </template>
      <transition name="component-change" mode="out-in">
        <keep-alive :max="10">
          <component :is="currentApp === componentName ? componentName : ''" ref="componentRef" :isComponent="true" @openApp="openApp" render="div" @cancel="visible = false" @hook:activated="refLoaded()"></component>
        </keep-alive>
      </transition>
      <nav-ref-list ref="navRefList" :title="navRefList.title" :navDatas="navRefList.dataList" @confirm="(row) => openApp(navRefList.currentNavCode, ...row)"></nav-ref-list>
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
/** 子组件 */
import headOfThisProject from './components/headOfThisProject'
import projectItemTab from './components/projectItemTab'
import projectDetail from './components/projectDetail'
import speedOfProgress from './components/speedOfProgress'
import projectOthersInfo from './components/projectOthersInfo'
import navRefList from '../../../components/common/navRefList'
import foldNavBar from '../../../components/common/foldNavBar'
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [],
  components: {
    headOfThisProject,
    projectItemTab,
    projectDetail,
    speedOfProgress,
    projectOthersInfo,
    navRefList,
    foldNavBar
  },
  data() {
    return {
      url: {
        queryMmsDataInfo: process.env.MSP_API + '/msp/dataRelation/queryMmsDataInfo1'
      },
      visible: false,
      mainHeight: 1000,
      mainScrollElement: null,
      defaultApp: 'projectinfo',
      currentApp: 'projectinfo',
      componentName: '',
      navRefList: {
        title: '',
        dataList: [],
        currentNavCode: ''
      },
      navList: [
        { name: '客户', count: 0, flag: null, on: false, code: 'customerinfo', useIframe: true, frameUrl: process.env.MCR_URL + '/dynamic', framePathList: { CpCustomerCompany: 'cp/cpCustomerCompany/fullEdit', CpCustomerCompanyOther: 'cp/cpCustomerCompanyOther/fullEdit' } },
        { name: '线索', count: 0, flag: null, on: false, code: 'leadinfo', useIframe: true, frameUrl: process.env.LTC_URL + '/dynamic', framePath: 'ltc/ltcLeadBackbone/fullEdit' },
        { name: '机会点', count: 0, flag: null, on: false, code: 'chanceinfo', useIframe: true, frameUrl: process.env.LTC_URL + '/dynamic', framePath: 'ltc/ltcChanceBackbone/fullEdit' },
        { name: '销售项目', count: 0, flag: null, on: false, code: 'projectinfo', useIframe: true, frameUrl: process.env.MPM_URL + '/dynamic', framePath: 'mpm/projectInfo/indexComp' },
        { name: '投标', count: 0, flag: null, on: false, code: 'bidinfo', useIframe: true, frameUrl: process.env.MMS_URL + '/dynamic', framePath: 'mmsui/ltcBidApply/indexFrame' },
        { name: '合同', count: 0, flag: null, on: false, code: 'contractinfo', useIframe: true, frameUrl: process.env.LTC_URL + '/dynamic', framePath: 'ltc/ltcContractApply/fullEdit' },
        { name: '交付', count: 0, flag: null, on: false, code: 'deliverinfo', useIframe: true, frameUrl: process.env.SD_URL + '/dynamic', framePath: 'sd/sdProjectInfo/indexComp' }
        /* { name: '订单', count: 0, flag: null, on: false, code: 'orderinfo', useIframe: false },
        { name: '交付', count: 0, flag: null, on: false, code: 'deliverinfo', useIframe: false },
        { name: '回款', count: 0, flag: null, on: false, code: 'paybackinfo', useIframe: false } */
      ],
      loading: false,
      projectinfo: {},
      projectRoleCode: 1,
      id: '',
      disableEditSubmit: false,
      // 流程组合页面额外参数
      extendIframeParam: {},
      // 重载用
      isIframeRefresh: true
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    },
    projectcode: {
      type: String,
      default: ''
    },
    // 标识父页面是否为流程组合页面
    isChildFrame: {
      type: Boolean,
      default: false
    },
    // 作为子页面打开时，是否是组件
    isComponent: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    // 检查是否作为子页面中打开
    isChildPage() {
      return (window.__POWER_BY_TAP_DYNAMIC && this.isChildFrame) || this.isComponent
    },
    // 是否作为组件打开
    isShowComponent() {
      let defaultItem = this.navList.find((m) => m.code === this.defaultApp)
      if (!defaultItem || !defaultItem.frameUrl) {
        return false
      }
      let url = defaultItem.frameUrl.substring(0, defaultItem.frameUrl.length - 8)
      return (item) => {
        if (item.code === this.defaultApp) {
          return false
        }
        return new RegExp(url).test(item.frameUrl)
      }
    }
  },
  methods: {
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        this.mainScrollElement = document.getElementById('mpmFileMainContainer').getElementsByClassName('el-scrollbar__wrap')[0]
        this.onMainScroll()
        this.loadProjectInfo()
        this.initFrame()
        this.doQueryNavList(this.id, this.defaultApp)
      })
    },
    /** 初始化iframe相关内容 */
    initFrame() {
      this.currentApp = this.defaultApp
      this.$nextTick(() => {
        // iframe内有时获取不到高度信息，需要重新加载
        if (this.isChildPage && this.mainHeight < 0) {
          this.$nextTick(() => {
            this.resizeHandler()
          })
        }
        this.navList.forEach((item) => {
          // 初始化侧边栏信息
          item.on = item.code === this.defaultApp
          item.count = 0
          // 如果在子页面内打开，或是本系统的组件，则不加载iframe
          if (this.isChildPage || this.isShowComponent(item) || item.code === this.defaultApp) {
            if (this.isShowComponent(item) && !item.loaded) {
              this.$options.components[item.code] = () => import(`@/views/${item.framePath}`)
            }
            item.useIframe = false
          } else if (item.useIframe && !item.loaded) {
            this.$refs['frame_' + item.code][0].prefetch()
          }
          item.loaded = true
        })
      })
    },
    /** 查询侧边栏数量 */
    doQueryNavList(id, code, extendParam) {
      if (this.$tap.validate.validateNull(id) || id <= 0) {
        return
      }
      // 获取侧边栏中的数量
      let param = {
        id: id,
        code: code
      }
      param = { ...param, ...extendParam }
      getAction(this.url.queryMmsDataInfo, param)
        .then((res) => {
          this.navList.forEach((item) => {
            let itemList = res[item.code]
            if (!this.$tap.validate.validateNull(itemList)) {
              item.count = itemList.length
              item.loadedList = itemList
            }
          })
        })
        .catch((err) => {
          console.error('侧边栏加载失败' + err)
        })
    },
    /** 点击左侧导航 */
    clickNav(code) {
      let app = this.navList.find((m) => m.code === code)
      if (app.code === this.defaultApp) {
        return
      }
      if (app.count === 1) {
        if (!app.loadedList[0].viewable) {
          this.$tap.alert('没有查看权限!', 'warning')
          return
        }
        this.openApp(app.code, ...app.loadedList)
      } else if (app.count > 1) {
        // 有多个选择时打开参照
        this.navRefList.title = `选择${app.name}`
        this.navRefList.dataList = app.loadedList
        this.navRefList.currentNavCode = app.code
        this.$refs['navRefList'].visible = true
      }
    },
    /** 打开对应的子页面 */
    openApp(code, appDatas) {
      if (!this.beforeOpenApp(code, appDatas)) {
        return
      }

      let { id, type } = appDatas
      // 有多个跳转页面的需要改变组件地址
      let app = this.navList.find((item) => item.code === code)
      if (app.framePathList && type) {
        app.framePath = app.framePathList[type]
      }

      let datas = {
        id: id,
        visible: true,
        disableEditSubmit: false,
        extendIframeParam: appDatas
      }

      if (code === this.defaultApp) {
        // 重载本页面
        this.reloadApp(appDatas)
      } else if (this.isShowComponent(app)) {
        // 加载子组件
        this.componentName = ''
      } else if (app.useIframe && app.loaded && (!app.iframeDatas || app.iframeDatas.id !== id)) {
        // 加载iframe
        this.currentApp = ''
        app.iframeDatas = datas
        this.$refs['frame_' + code][0].prefetchLoad()
      }
      // 延迟执行，保证子页面状态刷新
      this.$nextTick(() => {
        app.iframeDatas = datas
        if (this.isShowComponent(app)) {
          this.componentName = code
        }
        this.currentApp = code
      })
    },
    beforeOpenApp(code, appDatas) {
      if (this.isChildPage) {
        this.$emit('openApp', code, appDatas)
        return false
      } else {
        // 主页面监听到emit事件时调整侧边栏状态
        this.navList.forEach((m) => (m.on = m.code === code))
        return true
      }
    },
    refLoaded() {
      // 进入子组件时调用
      let { iframeDatas } = this.navList.find((item) => item.code === this.componentName || (item.framePathList && item.framePathList[this.componentName]))
      this.$nextTick(() => {
        if (this.$refs['componentRef'].id === iframeDatas.id) {
          return
        }
        this.$refs['componentRef'].id = iframeDatas.id
        this.$refs['componentRef'].extendIframeParam = iframeDatas.extendIframeParam
        this.$refs['componentRef'].disableEditSubmit = false
        this.$refs['componentRef'].visible = true
        this.$refs['componentRef'].open()
      })
    },
    iframeOpen() {
      // iframe启动用，防止抽屉页调用两次open
    },
    reloadApp(appDatas) {
      let { id, type } = appDatas
      if (this.id === id) {
        return
      }
      this.id = id
      this.extendIframeParam = appDatas
      this.disableEditSubmit = false
      this.isIframeRefresh = false
      this.$nextTick(() => {
        this.isIframeRefresh = true
        this.open()
      })
    },
    doCancelEdit() {
      if (this.isChildPage) {
        this.$emit('cancel')
      } else {
        this.visible = false
      }
      if (this.render === 'div') {
        this.close()
      }
      // this.$refs.drawerRef.closeDrawer()
    },
    close() {
      if (!this.disableEditSubmit) {
        this.$emit('refresh')
      }
      Object.assign(this.$data, this.$options.data.call(this))
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date ? date.toString().replace(/\-/g, "/") : date), "yyyy-MM-dd")
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {},
    loadProjectInfo() {
      getAction('mpm/project/load', { id: this.id }).then((result) => {
        this.projectinfo = result.result
        this.getProjectRoleCode()
        this.setProjectRole()
      })
      // 业务配置 vue组件管理中的可编辑字段 控制运作or监管下面挂载mpmxxx或mpmxxxQuery
      this.$refs.projectItemTabComponent.editFlag = 0
    },
    getProjectRoleCode() {
      this.projectRoleCode = 1
    },
    setProjectRole() {
      if (this.$store.getters.user.code === this.projectinfo.projectmanagercode) {
        this.$store.commit('SET_ROLES', ['pm', 'center'])
      } else {
        this.$store.commit('SET_ROLES', ['center'])
      }
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
    this.$once('hook:beforeDestroy', () => {
      // 抽屉组件必有
      window.removeEventListener('resize', this.resizeHandler)
    })
  },
  mounted() {},
  destroyed() {
    // 当切出运作tab时，重置角色
    this.$store.commit('SET_ROLES')
  }
}
</script>
<style scoped lang="scss">
.longTitle {
  text-overflow: ellipsis;
  max-width: 950px;
  white-space: nowrap;
  overflow: hidden;
}
/deep/ .el-tag--dark {
  border-color: #fff;
  color: #fff;
}
</style>
